import { addActivity, getAllClass, getAllRole } from "../../utils/request/api";
import msg from "../../utils/msg";
import { formatTime, Throttle } from '../../utils/util';
import User from "../../utils/user";
const throttle = Throttle();
var user = new User;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    addContent: {
      title: '' as string,
      place: '' as string,
      start_time: '' as string,
      end_time: '' as string,
      people: user.name as string,
      content: '' as string,
      grade: '' as string,
      class: [] as string[],
      classes: '' as string,//传入后端的班级数据，各个班级之间以逗号分隔
      role: [] as string[],
      roles: '' as string,
      need: 0 as number,
      limit: 0 as number,
      lat:0 as number,
      lon:0 as number,
      radius:200 as number,
      sign_start:10 as number,
      sign_late_start:2 as number,
      sign_end:5 as number,
    },
    user:user,
    columns: [
      {
        values: [] as Array<string>,
        className: 'column1',
      },
      {
        values: [] as Array<string>,
        className: 'column2',
        defaultIndex: 0,
      },
    ],
    marker: [],//地图签到点
    StartDay: '',//开始日期
    show: false,
    showClass: false,
    showRole: false,
    showtime1: false,
    showtime2: false,
    showtime3: false,
    showDetail:false,
    showyn: false,
    minHour: 0,
    maxHour: 24,
    currentDate: new Date().getTime(),
    currentTime: `12:00`,
    //数据格式如 {2021:[计科一班，计科二班]，2022:[网工一班，网工二班]}；
    AllClasses: {} as { [key: string]: Array<string> },
    AllRoles: [] as Array<string>,
    grades: [] as string[],//前端显示的
    classes: [] as string[],//通过用户选择的年级显示对应班级
    roles: [] as string[],
    yn: ['是', '否'],//是否强制参加
  },
  //已发布活动
  goToActicityHistory(){
      wx.navigateTo({
          url:'/pages/activity/activityHistory/activityHistory',
      })
  },
  //提交
  submit: async function () {
    if (!this.checkData()) return;
    msg.Loading('正在发布');
    await throttle(2000)
      .then(async () => {
        console.log('发布');
        await addActivity(this.data.addContent)
          .then(async () => {
            msg.hideLoading();
            await msg.show('发布成功', '');
            wx.navigateBack();
          })
          .catch(() => {
            msg.show('发布失败', '系统维护中');
          })
        msg.hideLoading();
      })
      .catch(() => {
        // 触发节流
        msg.show('请勿重复点击', '');
      })
  },
  //设置签到点
  _setMarker(lat: number, lng: number) {
    const marker = {
      id: 0,
      width: '30px',
      height: '40px',
      latitude: lat,
      longitude: lng,
      label: {
        content: '签到点',  //文本
        color: '#FF0202',  //文本颜色
        borderRadius: 3,  //边框圆角
        borderWidth: 1,  //边框宽度
        borderColor: '#FF0202',  //边框颜色
        bgColor: '#ffffff',  //背景色
        padding: 5,  //文本边缘留白
        textAlign: 'center'  //文本对齐方式。有效值: left, right, center
      },
    }
    this.setData({ ['marker[0]']: marker });
  },
  //更改签到细节
  editDetail(){
    this.setData({
        showDetail:true,
    });
  },
  //选择签到点
  chooseLocation() {
    var self = this;
    wx.chooseLocation({
      success: function (lb) { 
        let latitude = lb.latitude;
        let longitude = lb.longitude;
        let addContent=self.data.addContent;
        addContent.lat=latitude;
        addContent.lon=longitude;
        //console.log('lb=',lb);
        self.setData({
            addContent:addContent,
        });
        self._setMarker(latitude,longitude);
      },
      complete: function (lb:any) {
      },
      cancel: function (lb:any) {
      },
      fail: function (lb) {
        console.log(lb);
        msg.show('获取签到地点失败','请重试');
      }
    });
  },
  //检查数据不能为空
  checkData() {
    let addContent: any = this.data.addContent;
    for (let key of Object.keys(addContent)) {
      //console.log(key + ': ' + addContent[key]);
      if (!addContent[key] && key != 'classes' && key != 'roles' && key != 'class' && key != 'role'&&addContent['need'] != 0) {
        msg.show('有信息未填写', '请填写完整表单后再提交');
        return false;
      }
    };
    if(this.data.addContent.class.length==0){
        msg.show('请填写至少一个班级','');return;
    }
    if(this.data.addContent.lat==0){
        msg.show('请选择签到地点','');return;
    }
    //没问题，就将活动日期与开始结束时间融合
    let addContent2 = this.data.addContent;
    let end_time = this.data.StartDay + ' ' + addContent2.end_time;
    addContent2.end_time = formatTime(new Date(end_time));
    let start_time = this.data.StartDay + ' ' + addContent2.start_time;
    addContent2.start_time = formatTime(new Date(start_time));
    this.setData({
      addContent: addContent2,
    })
    return true;
  },
  //获取输入
  getInput(e: any) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ['addContent.' + index]: e.detail.value,
    });
  },
  //获取开始日期
  onChooseTime3(e: any) {
    this.setData({
      showtime3: true,
    });
  },
  //获取开始日期
  getDayStart(e: any) {
    let format_time = formatTime(new Date(e.detail));
    let time = format_time.split(' ');
    this.setData({
      StartDay: time[0],
      showtime3: false,
    });
  },
  //获取开始时间
  getInputStart(event: any) {
    let addContent = this.data.addContent;
    addContent.start_time = event.detail;
    console.log(addContent.start_time);
    this.setData({
      addContent: addContent,
      showtime1: false,
    });
  },

  //获取结束时间
  getInputEnd(event: any) {
    let addContent = this.data.addContent;
    addContent.end_time = event.detail;
    this.setData({
      addContent: addContent,
      showtime2: false,
    });
  },

  //获取是否强制参加
  getInputYN(event: any) {
    let addContent = this.data.addContent;
    if (event.detail.value == '是') {
      addContent.need = 1;
    }
    else {
      addContent.need = 0;
    }
    this.setData({
      addContent: addContent,
      showyn: false,
    });
  },

  //关闭弹窗
  onClose() {
    this.setData({
      show: false,
      showClass: false,
      showtime1: false,
      showtime2: false,
      showtime3: false,
      showyn: false,
      showRole: false,
      showDetail:false,
    })
  },

  //选择年级弹窗
  onChoose() {
    this.setData({
      show: true,
    })
  },
  //选择班级弹窗
  onChooseClass() {
    this.setData({
      showClass: true,
    })
  },

  //选择职务弹窗
  onChooseRole() {
    this.setData({
      showRole: true,
    })
  },

  //选择开始时间弹窗
  onChooseTime1() {
    this.setData({
      showtime1: true,
    })
  },

  //选择结束时间弹窗
  onChooseTime2() {
    this.setData({
      showtime2: true,
    })
  },

  //选择是否强制参加的弹窗
  onSet() {
    this.setData({
      showyn: true,
    })
  },
  //返回
  onClickLeft() {
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function () {
    await getAllClass()
      .then((res: any) => {
        let classes: { [key: string]: Array<string> } = res.data.data;
        this.setData({
          AllClasses: classes,
          grades: Object.keys(classes),
        });
      });
      await getAllRole()
      .then((res: any) => {
        let roles: Array<string> = res.data.data;
        this.setData({
          AllRoles: roles,
        });
      });
  },

  //  年级-班级选择逻辑
  gradeConfirm(event: any) {
    const { picker, value, index } = event.detail;
    let addContent = this.data.addContent;
    addContent.grade = value;
    addContent.class = this.data.AllClasses[value];
    let class_temp = '' as string;
    this.data.AllClasses[value].forEach((item) => {
      class_temp += item + ',';
    });
    this.data.addContent.classes = this.removeCommaEnd(class_temp);
    this.setData({
      addContent: addContent,
      classes: this.data.AllClasses[value],
      show: false,
    });
  },

  //  职务选择逻辑
  roleConfirm(event: any) {
    let addContent = this.data.addContent;
    addContent.role = this.data.AllRoles;
    let role_temp = '' as string;
    this.data.AllRoles.forEach((item) => {
      role_temp += item + ',';
    });
    this.data.addContent.roles = this.removeCommaEnd(role_temp);
    this.setData({
      addContent: addContent,
      roles: this.data.AllRoles,
      show: false,
    });
  },

  onChangeR(event: any) {
    let addContent = this.data.addContent;
    addContent.role = event.detail;
    let role_temp = '' as string;
    event.detail.forEach((item: any) => {
      role_temp += item + ',';
    });
    addContent.roles = this.removeCommaEnd(role_temp);
    this.setData({
      addContent: addContent,
    });
  },

  onChange(event: any) {
    let addContent = this.data.addContent;
    addContent.class = event.detail;
    let class_temp = '' as string;
    event.detail.forEach((item: any) => {
      class_temp += item + ',';
    });
    addContent.classes = this.removeCommaEnd(class_temp);
    this.setData({
      addContent: addContent,
    });
  },
  toggle(event: any) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  //去掉字符串末尾的逗号
  removeCommaEnd(input: string): string {
    let processedInput = input.trim(); // 去掉字符串前后的空格
    while (processedInput.endsWith(',')) {
      processedInput = processedInput.slice(0, -1); // 去掉字符串末尾的逗号
    }
    return processedInput;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})